package com.yf.exam.modules.tmpl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.base.utils.BeanMapper;
import com.yf.exam.modules.tmpl.dto.ext.TmplRuleDetailDTO;
import com.yf.exam.modules.tmpl.entity.TmplGroupRule;
import com.yf.exam.modules.tmpl.mapper.TmplGroupRuleMapper;
import com.yf.exam.modules.tmpl.service.TmplGroupRuleService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
* <p>
* 大题组卷规则业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2021-04-25 13:59
*/
@Service
public class TmplGroupRuleServiceImpl extends ServiceImpl<TmplGroupRuleMapper, TmplGroupRule> implements TmplGroupRuleService {

    @Override
    public void saveAll(String groupId, List<TmplRuleDetailDTO> ruleList) {

        // 当前存在的ID
        List<String> ids = this.findIds(groupId);

        if(!CollectionUtils.isEmpty(ruleList)) {

            for(TmplRuleDetailDTO item: ruleList){
                TmplGroupRule qu = new TmplGroupRule();
                BeanMapper.copy(item, qu);
                qu.setGroupId(groupId);

                this.saveOrUpdate(qu);
                // 移除存在的
                ids.remove(item.getId());
            }
        }

        if(!CollectionUtils.isEmpty(ids)){
            this.delete(ids);
        }
    }

    @Override
    public void removeByGroups(List<String> groupIds) {

    }

    @Override
    public List<TmplGroupRule> listByGroup(String groupId) {
        QueryWrapper<TmplGroupRule> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(TmplGroupRule::getGroupId, groupId);
        return this.list(wrapper);
    }


    /**
     * 查找已存在列表
     * @param groupId
     * @return
     */
    private List<String> findIds(String groupId){
        QueryWrapper<TmplGroupRule> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(TmplGroupRule::getId)
                .eq(TmplGroupRule::getGroupId, groupId);
        List<TmplGroupRule> list = this.list(wrapper);
        List<String> ids = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            for (TmplGroupRule item: list){
                ids.add(item.getId());
            }
        }
        return ids;
    }


    /**
     * 根据ID删除
     * @param ids
     */
    private void delete(List<String> ids) {
        QueryWrapper<TmplGroupRule> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(TmplGroupRule::getId, ids);
        this.remove(wrapper);
    }
}
